package cn.bonoon.kernel.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class AuthenticatedUserDetails {

	/**
	 * Returns the userid of an authenticated user.
	 * 
	 * @return the userid if the user is logged in otherwise null
	 */
	public Long getPrincipal() {
		return getUser().getId();
	}

	public LogonUser getUser() {
		return user(LogonUser.class);
	}
	
	@SuppressWarnings("unchecked")
	protected <T> T user(Class<T> cls){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (null != authentication) {
			Object principal = authentication.getPrincipal();
			if(cls.isInstance(principal)) return (T)principal;
		}
		return null;
	}

	public String getPrincipalName() {
		return getUser().getDisplayName();
	}
	
	public String getUsername(){
		return getUser().getUsername();
	}
	
	public boolean isActing(){
		LogonUserProxyable user = user(LogonUserProxyable.class);
		return null != user && user.isActing();
	}
	
	public boolean isProxyable(){
		LogonUserProxyable user = user(LogonUserProxyable.class);
		return null != user && user.isProxyable();
	}
	
	public boolean isNeedChangePwd(){
		LogonUser user = user(LogonUser.class);
		return null != user && user.getRuntime().needChangePwd();
	}
}
